from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_jwt_extended import JWTManager
from flask_cors import CORS
from flask_bcrypt import Bcrypt
from config import config
from loguru import logger
import os

# 初始化扩展
db = SQLAlchemy()
jwt = JWTManager()
bcrypt = Bcrypt()

def create_app(config_name='development'):
    """应用工厂函数"""
    app = Flask(__name__)
    
    # 加载配置
    app.config.from_object(config[config_name])
    
    # 初始化扩展
    db.init_app(app)
    jwt.init_app(app)
    bcrypt.init_app(app)
    CORS(app)
    
    # 配置日志
    logger.add(
        os.path.join(app.root_path, '..', 'logs', 'app.log'),
        rotation='1 day',
        retention='30 days',
        level='INFO'
    )
    
    # 注册蓝图
    from .api.auth import auth_bp
    from .api.articles import articles_bp
    from .api.questions import questions_bp
    from .api.exams import exams_bp
    from .api.certificates import certificates_bp
    from .api.leaderboards import leaderboards_bp
    from .api.users import users_bp
    from .api.system import system_bp
    
    app.register_blueprint(auth_bp, url_prefix='/api/auth')
    app.register_blueprint(articles_bp, url_prefix='/api/articles')
    app.register_blueprint(questions_bp, url_prefix='/api/questions')
    app.register_blueprint(exams_bp, url_prefix='/api/exams')
    app.register_blueprint(certificates_bp, url_prefix='/api/certificates')
    app.register_blueprint(leaderboards_bp, url_prefix='/api/leaderboards')
    app.register_blueprint(users_bp, url_prefix='/api/users')
    app.register_blueprint(system_bp, url_prefix='/api/system')
    
    # 创建数据库表
    # with app.app_context():
    #     db.create_all()
    #     logger.info("数据库表创建完成")
    
    return app 